package com.dcy.znoa.controller.conference;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.excel.ExcelOutput;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.conference.model.conference.AddConferenceModel;
import com.dcy.znoa.controller.conference.model.conference.SelectConferenceModel;
import com.dcy.znoa.controller.conference.model.conference.UpdateConferenceModel;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.conference.Conference;
import com.dcy.znoa.domain.conference.ConferenceVo;
import com.dcy.znoa.service.conference.ConferenceService;

/**
 * @author chenjie
 */
@Controller
@RequestMapping("conference")
public class ConferenceController extends BaseController {
    @Autowired
    ConferenceService conferenceService;

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectList")
    public JsonForList selectList(SelectConferenceModel selectConferenceModel) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//查询本公司会议  H5
    	if (null != selectConferenceModel.getStartTimeStr() && !selectConferenceModel.getStartTimeStr().isEmpty()) {
			if (null == selectConferenceModel.getEndTimeStr() || selectConferenceModel.getEndTimeStr().isEmpty()) {
				return  new JsonForList("404","有开始时间，必需有结束时间！");
			}
		}
    	Oper oper = getCurrentUser();
    	selectConferenceModel.setCompId(oper.getCompId());
    	selectConferenceModel.setCreateOperId(oper.getOperId());
        return conferenceService.selectList(selectConferenceModel);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectById")
    public JsonCommon selectById(Long confId) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//查询会见详情
    	if (confId == null) {
    		return  new JsonCommon("404","缺少参数");
		}
    	
        return conferenceService.selectById(confId);
    } 
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/myNotFinished")
    public JsonForList myNotFinished(SelectConferenceModel selectConferenceModel) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//未结束的
    	Oper oper = getCurrentUser();
    	selectConferenceModel.setCompId(oper.getCompId());
    	selectConferenceModel.setCreateOperId(oper.getOperId());
        return conferenceService.myNotFinished(selectConferenceModel);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/insert")
    public JsonCommon insert(@Valid AddConferenceModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }
        if(model.getConferSubject().length()>50){
            return  new JsonCommon("404","会议名称长度不能大于50");
        }
        if(null == model.getOperIds() || model.getOperIds().length < 1){
            return  new JsonCommon("404","参会人员不能为空");
        }
        Oper oper = getCurrentUser();
    	model.setCreateOperName(oper.getOperName());
        model.setCompId(getCurrentUser().getCompId());
        model.setCreateOperId(oper.getOperId());
        
        Conference conference = new Conference();
        BeanUtils.copyProperties(conference, model);
        conference.setQrCode(getConferenceQrByUUId(conference.getCompId()));
        try {
			conference.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(model.getStartTimeStr()));
			conference.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(model.getEndTimeStr()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
        
        
        return conferenceService.insert(conference,model.getOperIds());
        //插入会议后，保存会议预约记录  ---------------------------会议预约记录是否需要，有什么用
        //插入会议后，保存会议参会人员
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/cancelConference")
    public JsonCommon cancelConference(@Valid UpdateConferenceModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        //撤销会议
    	if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }
        
        model.setUpdateOperName(getCurrentUser().getOperName());
        Conference conference = new Conference();
        BeanUtils.copyProperties(conference, model);
        conference.setUpdateOperId(getCurrentUser().getOperId());
        conference.setValidFlag(0);
        return conferenceService.cancelConference(conference);
    }

    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/myCreateConference")
    public JsonForList myCreateConference(SelectConferenceModel selectConferenceModel) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//我发起的会议
    	Oper oper = getCurrentUser();
    	selectConferenceModel.setCompId(oper.getCompId());
    	selectConferenceModel.setCreateOperId(oper.getOperId());
        return conferenceService.selectMyCreateConference(selectConferenceModel);
    }  
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/myCreateConferenceDetail")
    public JsonCommon myCreateConferenceDetail(Long confId) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//发起的会议详情
    	if (null == confId) {
            return  new JsonCommon("404","会议ID不能为空");
		}
        return conferenceService.myCreateConferenceDetail(confId);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/myReceiveConference")
    public JsonForList myReceiveConference(SelectConferenceModel selectConferenceModel) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//我收到的会议
    	Oper oper = getCurrentUser();
    	selectConferenceModel.setCompId(oper.getCompId());
    	selectConferenceModel.setCreateOperId(oper.getOperId());
        return conferenceService.myReceiveConference(selectConferenceModel);
    }  
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/myReceiveConferenceDetail")
    public JsonCommon myReceiveConferenceDetail(Long confId) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//我收到的会议详情  通过confId  查询会议详情  我的回执、签到、取消   等详情
    	if (null == confId) {
            return  new JsonCommon("404","会议ID不能为空");
		}
    	Oper oper = getCurrentUser();
    	SelectConferenceModel selectConferenceModel =new SelectConferenceModel();
    	selectConferenceModel.setConfId(confId);
    	selectConferenceModel.setCreateOperId(oper.getOperId());
        return conferenceService.myReceiveConferenceDetail(selectConferenceModel);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/conferenceOfRoomAndDay")
    public JsonForList conferenceOfRoomAndDay(SelectConferenceModel selectConferenceModel) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//会议室：该会议室当天所有会议列表
    	if (selectConferenceModel.getConferId() == null) {
            return  new JsonForList("404","会议室ID不能为空");
		}
    	if (null == selectConferenceModel.getDayTime() || selectConferenceModel.getDayTime().isEmpty()) {
            return  new JsonForList("404","日期不能为空");
		}
    	
        return conferenceService.conferenceOfRoomAndDay(selectConferenceModel);
    }
    
    
    //会议二维码生成
    public static String getConferenceQrByUUId(Long compId ) {
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {//有可能是负数
            hashCodeV = - hashCodeV;
        }
        // 0 代表前面补充0     
        // 4 代表长度为4     
        // d 代表参数为正数型
        return compId + String.format("%015d", hashCodeV);
    }
    
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/export")
    public JsonCommon export(SelectConferenceModel selectConferenceModel,BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws BusinessException, InvocationTargetException, IllegalAccessException, IOException {
        if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }

      //查询本公司会议  H5
    	if (null != selectConferenceModel.getStartTimeStr() && !selectConferenceModel.getStartTimeStr().isEmpty()) {
			if (null != selectConferenceModel.getEndTimeStr() || selectConferenceModel.getEndTimeStr().isEmpty()) {
				return  new JsonCommon("404","有开始时间，必需有结束时间！");
			}
		}
    	Oper oper = getCurrentUser();
    	selectConferenceModel.setCompId(oper.getCompId());
    	selectConferenceModel.setCreateOperId(oper.getOperId());

    	JsonForList jsonForList = conferenceService.selectList(selectConferenceModel);     
        
        List<Map<String, Object>> recordList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();//list转map
        List<ConferenceVo> list = jsonForList.getData();
        for (ConferenceVo conferenceVo :list) {
            recordList.add(ConferenceVo.toMap(conferenceVo));
        }
        
        String keys[] = {"confId", "createTime", "conferSubject", "startTime", "endTime", "conferAddress", "operAmount"};//map中的key
        String columnNames[] = {"ID", "创建时间", "会议主题", "开始时间", "结束时间", "地址", "参会人数"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "会议");
        
        return new JsonCommon(SUCCESS_CODE);
    }
}
